package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 今日佳人：
     *   根据touserId查询推荐用户，查询score最高的为用户即可 （RecommentUser）
     *   将RecommentUser 转化为 TodayBest的vo对象
     */
    public TodayBest todayBest() {
        //1、获取当前用户id，查询条件
        Long toUserId = UserHolder.getUserId();
        //2、调用API，根据touserId查询缘分值最高的推荐数据
        RecommendUser user = recommendUserApi.findWithMaxScore(toUserId);
        //针对新用户，并没有推荐
        if(user == null) {
            //构造假数据
            user = new RecommendUser();
            user.setToUserId(toUserId);
            user.setUserId(1l); //推荐
            user.setScore(95d);
        }
        //3、TodayBest根据userId,查询需要推荐用户的信息
        UserInfo userInfo = userInfoApi.findById(user.getUserId());
        //4、将RecommentUser 转化为 TodayBest
        return TodayBest.init(userInfo,user);
    }

    /**
     * 分页查询推荐的用户数据
     *  前端：分页的时候并不需要总数
     *  实质：调用API分页查询时，只需要数据列表就够了
     */
    public PageResult recommendation(Integer page, Integer pagesize) {
        //1、获取当前用户id，查询条件
        Long toUserId = UserHolder.getUserId();
        //2、调用API，根据toUserId分页查询数据列表  List<RecommentUser>
        List<RecommendUser> list = recommendUserApi.findRecommentUserList(toUserId,page,pagesize);
        //3、对于新用户没有推荐数据，构造默认数据
        if(CollUtil.isEmpty(list)) {
            list = defaultList();
        }
        //4、将一个RecommentUser转化成一个TodayBest的vo对象  List<TodayBest>
        List<TodayBest> vos = new ArrayList<>();
        for (RecommendUser user : list) {
            UserInfo userInfo = userInfoApi.findById(user.getUserId());
            TodayBest vo = TodayBest.init(userInfo, user);
            vos.add(vo);
        }
        //5、构造返回值PageResult
        return new PageResult(page,pagesize,0l,vos);
    }


    private List<RecommendUser> defaultList() {
        List<RecommendUser> list = new ArrayList<>();
        //构造默认推荐数据，企业中按照项目经理要求
        for (int i = 1; i <= 10; i++) {
            RecommendUser ru = new RecommendUser();
            ru.setUserId((long) i); //模拟推荐的用户id
            ru.setScore(95D); //模拟推荐的评分
            list.add(ru);
        }
        return list;
    }

    //查看佳人详情
    public TodayBest personalInfo(Long userId) {
        //1、用户信息
        UserInfo userInfo = userInfoApi.findById(userId);
        //2、推荐数据（缘分值）
        Long toUserId = UserHolder.getUserId();
        RecommendUser user = recommendUserApi.queryByUserId(userId,toUserId);
        //3、返回
        return TodayBest.init(userInfo,user);
    }

    //查看用户的陌生人问题
    public String strangerQuestions(Long userId) {
        Question question = questionApi.findByUserId(userId);
        return question == null ? "你喜欢java吗？": question.getTxt();
    }

    //回复陌生人问题
    public void reply(Long userId, String reply) {
        //{"userId":106,
        // "huanXinId":"hx106",
        // "nickname":"黑马小妹"
        //1、构造数据
        Map map = new HashMap();
        map.put("strangerQuestion",strangerQuestions(userId));
        map.put("reply",reply);
        //获取当前用户信息
        Long currtId = UserHolder.getUserId();
        UserInfo userInfo = userInfoApi.findById(currtId);
        map.put("nickname",userInfo.getNickname());
        map.put("huanXinId","hx"+currtId);
        map.put("userId",currtId);
        //2、发送消息
        String msg = JSON.toJSONString(map);
        huanXinTemplate.sendMsg("hx"+userId,msg);//环信用户，消息内容
    }

    @DubboReference
    private UserLocationApi userLocationApi;

    //搜索附近
    public List<NearUserVo> search(String gender, String distance) {
        Long userId = UserHolder.getUserId();
        //1、调用API查询附近的地理位置，返回附近人的用户id集合
        List<Long> userIds = userLocationApi.searchNear(userId,distance); //当前用户id，距离
        //2、查询附近人的用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds);
        //3、构造vo对象返回即可
        List<NearUserVo> vos = new ArrayList<>();
        for (Long id : userIds) {
            //排除自己，当附近的人的用户id==当前用户id是，不在构造vo对象
            if(id == userId) {
                continue;
            }
            UserInfo info = map.get(id);
            //性别的筛选
            if(!gender.equals(info.getGender())) {
                continue;
            }
            NearUserVo vo = NearUserVo.init(info);
            vos.add(vo);
        }
        return vos;
    }
}
